import auth from './auth.js';

export const http = {
  /* #ifdef MP-WEIXIN */
  baseURL: wx.getAccountInfoSync().miniProgram.envVersion === 'release' || 
          wx.getAccountInfoSync().miniProgram.envVersion === 'trial'
          ? "https://fuxing.guangdongyangjiang.cn/api"
          : "http://127.0.0.1:9999/api",
  /* #endif */
  
  /* #ifndef MP-WEIXIN */
    /* #ifdef H5 */
    baseURL: "http://127.0.0.1:9999/api",
    /* #endif */
    
    /* #ifndef H5 */
    baseURL: "https://fuxing.guangdongyangjiang.cn/api",
    /* #endif */
  /* #endif */
  timeout: 10000, // 添加默认超时时间

  async request(options) { 
    const token = auth.getToken();
    // 统一处理请求配置
    const requestConfig = {
      ...options,
      timeout: options.timeout || this.timeout,
      url: options.url.startsWith('http') ? options.url : this.baseURL + options.url,
      header: {
        ...options.header,
        'auuua': token  // 修改为新的请求头名称，移除Bearer前缀
      }
    };

    // 增强调试日志
    console.log('--请求路径--:', requestConfig.url);
    
    try {
      const response = await uni.request(requestConfig);
      console.log('--返回--:', response);

      // 统一响应处理
      if (response.statusCode >= 200 && response.statusCode < 300) {
        return response.data;
      }
      
      // 处理401未授权错误
      if (response.statusCode === 401) {
        uni.showToast({
          title: response.message,
          icon: 'none'
        });
        try {
          auth.clearTokens();
        } catch (refreshError) {
          setTimeout(() => {
            uni.reLaunch({ url: '/pages/login/index' });
          }, 1500);
          throw refreshError;
        }
      }

      // 其他错误处理
      throw {
        code: response.statusCode,
        message: response.data?.message || '请求失败'
      };
      
    } catch (error) {
      // 网络错误处理
      if (!error.statusCode) {
        uni.showToast({
          title: '网络连接失败',
          icon: 'none'
        });
      }
      throw error;
    }
  },

  // 便捷方法
  get(url, data = {}, options = {}) {
    return this.request({
      url,
      data: this._preprocessData(data, 'GET'),
      method: 'GET',
      ...options
    });
  },

  post(url, data = {}, options = {}) {
    return this.request({
      url,
      data: this._preprocessData(data, 'POST'), 
      method: 'POST',
      ...options
    });
  },

  put(url, data = {}, options = {}) {
    return this.request({
      url,
      data: this._preprocessData(data, 'PUT'),
      method: 'PUT',
      ...options
    });
  },

  delete(url, data = {}, options = {}) {
    return this.request({
      url,
      data: this._preprocessData(data, 'DELETE'),
      method: 'DELETE',
      ...options
    });
  },
  _preprocessData(data, method = 'GET') {
    if (!data) return {};
    return Object.keys(data).reduce((result, key) => {
      if (data[key] !== undefined) {
        // 只有GET请求且值为数组时才特殊处理
        if (method === 'GET' && Array.isArray(data[key])) {
          result[key] = data[key].join(',');
        } else {
          result[key] = data[key];
        }
      }
      return result;
    }, {});
  },
};

export default http;